package com.sz.test.listener;

import com.sz.test.annotation.Role;
import com.sz.test.context.SecurityContext;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.lang.reflect.Method;

@WebListener
public class ApplicationListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("-----项目启动了");
        try {
            Class<?> clazz = Class.forName("com.sz.test.controller.UserController");
            Method[] methods = clazz.getDeclaredMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                method.setAccessible(true);
                Role roleAnnotation = method.getAnnotation(Role.class);
                if (roleAnnotation != null) {
                    wrapperAnnotationValue(method, roleAnnotation.value());
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private void wrapperAnnotationValue(Method method, int roleValue) {
        PostMapping postMappingAnnotation = method.getAnnotation(PostMapping.class);
        GetMapping getMappingAnnotation = method.getAnnotation(GetMapping.class);
        DeleteMapping deleteMappingAnnotation = method.getAnnotation(DeleteMapping.class);
        String[] uriArr = null;
        String methodMapping = "";
        if (postMappingAnnotation != null) {
            methodMapping = "POST";
            uriArr = postMappingAnnotation.value();
        } else if (getMappingAnnotation != null) {
            methodMapping = "GET";
            uriArr = getMappingAnnotation.value();
        } else if (deleteMappingAnnotation != null) {
            methodMapping = "DELETE";
            uriArr = deleteMappingAnnotation.value();
        } else {
            return;
        }
        for (int j = 0; j < uriArr.length; j++) {
            SecurityContext.getMethodRequireRoleAndPerms().put(methodMapping+"-"+uriArr[j], roleValue);
        }
    }
}
